<template>
  <div class="flex-row autoGrow manageContainer">
    <choose-service-account
      :multiple="false"
      @serviceChange="serviceChange"
    >

    </choose-service-account>
    <div class="settingOption flex-column">
      <div class="subTitle">群列表</div>
      <div class="autoGrow welcomeOptions flex-column" v-if="service">
        <div class="toggleOwner">
          <label>
            <input type="radio"
            name="manager"
            value="manager"
            @change="changeGroupType"
            :checked="groupType=='manager'"> 群主
          </label>
          <label>
            <input type="radio"
            name="manager"
            value="member"
            @change="changeGroupType"
            :checked="groupType=='member'"> 非群主
          </label>
          
        </div>
        <search placeholder="请输入关键词" @change="changeSearch"></search>
        <div class="groupListTitle">
          群（{{filterGroups ? filterGroups.length : 0}}）
        </div>
        <div class="groupList autoGrow">
          <label v-for="(group) in filterGroups" :key="group.id">
            <user-list-item
              :showBadge="false"
              :showLastMessage="false"
              currentUserWxid=""
              :item="group">
              <template v-slot:checkbox>
                <input type="radio"
                  name="group"
                  :checked="currentGroup&&currentGroup.wxid == group.wxid"
                  class="select"
                  @change="changeCurrentGroup(group)">
              </template>
              <template v-slot:bottomInfo>
                <div>
                  <span>群成员{{group.personnum}} </span>
                  <span>非好友{{group.personnum - group.friendNum}}</span>
                </div>
              </template>
            </user-list-item>
            
          </label>
          
        </div>
      </div>
    </div>
    <div class="welcomeList flex-column autoGrow">
      <div class="listHead flex-row">
        <div class="flex-row">
          <div class="subTitle">群成员</div>
          <input type="text" class="layui-input searchMember" v-model="searchMember" placeholder="请输入搜索关键词">
        </div>
        <!-- <button class="layui-btn layui-btn-danger layui-btn-xs" v-if="currentGroup" @click="deleteGroup">解散该群</button> -->
      </div>
      <div class="tabs">
        <button :class="['tab', 'layui-btn', 'layui-btn-xs', curTab!='friend' && 'layui-btn-primary']" @click="changeTab('friend')">
          好友关系（{{friends.length}}）
        </button>
        <button :class="['tab', 'layui-btn', 'layui-btn-xs', curTab!='member' && 'layui-btn-primary']" @click="changeTab('member')">
          非好友关系（{{members.length}}）
        </button>
      </div>
      <div class="listContainer autoGrow flex-row" v-if="currentGroup">
        <div class="flex-row member-list-item" v-for="(user, i) in filteredUsers" :key="i">
          <friend 
            :avatar="user.avatar"
            :name="user.nick"
            :wxid="user.alias||user.wxid"
            :gender="user.sex"
            class="member-list-item-friend"
          />
          <div class="user-operate flex-column">
            <button class="layui-btn layui-btn-xs user-operate-button" v-if="curTab=='member'" @click="addFriend(user)">加好友</button>
            <button v-if="currentGroup.isfirst === 1" class="layui-btn layui-btn-xs layui-btn-danger user-operate-button" @click="deleteFromGroup(user, i)">踢出群</button>
          </div>
        </div>
      </div>
      <a v-if="service && currentGroup" href="javascript:" class="invite-button" @click="addGroupMember">邀请好友进群</a>
    </div>
    <custom-dialog title="解散群" wrapClass="dismissDialog" :showBtn="true" @submit="comfirmDismiss" :closeDialog="()=>this.showDismissDialog=false" v-if="showDismissDialog">
      <div class="dismissText">确定解散该群？解散后无法回复</div>
    </custom-dialog>
    <custom-dialog title="踢出该用户" wrapClass="deleteUserDialog" :showBtn="true" @submit="comfirmDeleteUser" :closeDialog="()=>this.showDeleteUserDialog=false" v-if="showDeleteUserDialog">
      <div class="dismissText">该用户在您是群主的{{groupsHasCurUser.length}}个群内，请选择是否踢出</div>
      <div class="dialogUserlist">

        <ul class="scrollAuto autoGrow checkList">
          <li class="flex-row serviceItem listItem" v-for="(item) in groupsHasCurUser" :key="item.id">
            <label style="width:100%" class="invite-item">
              <input type="checkbox" @change="selectGroup($event,item)" />
              <div class="invite-avatar">
                <img style="background:#ccc" :src="item.avatar" alt="">
              </div>
              <div class="invite-info">
                <span>{{item.groupname}}</span>
                <span class="fontGrey">
                  <span>群成员{{item.personnum}} </span>
                  <span>非好友{{item.personnum - item.friendNum}}</span>
                  </span>
              </div>
            </label>
          </li>
        </ul>

        <!-- <user-list-item
          v-for="(user, i) in groupsHasCurUser"
          :key="i"
          :item="user"
          :showBadge="false"
          :showLastMessage="false"
          :showGender="true"
        >
          <template v-slot:checkbox>
            <input type="checkbox"
              :checked="selectedDeleteGroup.filter(u=>u.wxid==user.wxid).length"
              @change="selectGroup(i, $event)">
          </template>
          <template v-slot:bottomInfo>
            <div>
              群成员{{user.memberCount}} 非好友{{user.memberCount-user.friendsCount}}
            </div>
          </template>
        </user-list-item> -->
      </div>
    </custom-dialog>
 
    <dialogSelectFriend ref="dialogSelectFriend" />
    <dialogSelectGroup ref="dialogSelectGroup" />
  </div>
</template>
<script>
import ChooseServiceAccount from '@/components/chooseServiceAccount'
import dialogSelectFriend from '@/components/dialog-select-friend'
import dialogSelectGroup from '@/components/dialog-select-group'
import UserListItem from '@/components/userListItem'
import QuickReplies from './quickReplies'
import CustomDialog from '@/components/customDialog'
import Search from '@/components/search'
import pinyin from '@/lib/pinyin'
import friend from '@/components/friend'
import group from '@/components/group'
import { mapActions } from 'vuex';

export default {
  name: 'memberManage',
  data() {
    return {
      showDismissDialog: false,
      showDeleteUserDialog: false,
      showInviteDialog:false,
      curTab: 'friend',
      currentGroup: null,
      currentFriend: null,
      service: null,
      groups: [],
      keyword: '',
      groupType: 'manager', // member
      searchMember: '',
      friends: [],
      members: [],
      selectedDeleteGroup: [],
      inviteFriends:[],
      checkedFriends:[],
      groupsHasCurUser:[]
    }
  },
  components: {
    ChooseServiceAccount,
    UserListItem,
    QuickReplies,
    CustomDialog,
    Search,
    friend,
    group,
    dialogSelectFriend,
    dialogSelectGroup
  },
  methods: {
    ...mapActions(['wsSend']),
    serviceChange(services) {
      this.service = services[0]
      this.init()
    },
    init() {
      this.$api.group.list({
        csid: this.service.csid,
        wxaccount: this.service.wxid
      }).then(data=>{
        this.groups = this.transGroupData(data);
      }).catch(e=>this.$msg(e))
    },

    async addGroupMember(){
      const { wxid,csid } = this.service;
      const { groupno } = this.currentGroup;

      const filterWxids = this.friends.map(item=>item.wxid)
      const selectFriends = await this.$refs.dialogSelectFriend.getSelectFriendsAsync({
        csid,
        wxaccount:wxid,
        multiple:true,
        filterType:1,
        type:1,
        filterWxids
      }) 
      if(selectFriends){
        this.$api.group.addFriend2Group({
          csId:csid, wxAccount:wxid, friendWxAccountList:selectFriends.map(item=>item.friendwxid) , groupNo:groupno
        }).then(rs=>{
          this.$message({
            type: 'success',
            message:'邀请成功'
          })
        })
      }
    },
 
    changeGroupType(e) {
      this.groupType = e.target.value
    },
    changeCurrentGroup(group) {
      this.currentGroup = group
      const members= [],friends = []
      this.$api.group.members({
        csId: this.service.csid,
        wxAccount: this.service.wxid,
        groupNo: group.groupno
      }).then(data=>{
        //data = this.transUserData(data);
        data.forEach(item=>{
          if(item.ismycontact === 1){
            friends.push(item)
          }else{
            members.push(item)
          }
        })
        this.members = members
        this.friends = friends
      })
    },
    changeSearch(val) {
      this.keyword = val
    },
    changeTab(tab) {
      this.curTab = tab
    },
    async deleteFromGroup(user, index) {
      console.log(user,index)
      const { csid,wxaccount,groupno,wxid,alias } = user
      const params = {
        csid,
        wxaccount,
        multiple:true,
        filterType:1,
        type:1,
        // filterNos,
        byMemberWxId:wxid,
        initialNos:[groupno],
        initialDisabled:true // 禁用
      }
      try {
        const rs = await this.$refs.dialogSelectGroup.getSelectFriendsAsync(params)
        console.log(rs)
        rs.forEach(group=>{
          this.$api.group.removeGroupMember({
            csId: group.csid,
            accountWxId: group.wxaccount,
            groupNo: group.groupno,
            memberWxId: wxid
          }).then(e=>{
            this.$msg('提交成功')
          }).catch(e=>this.$msg(e))
        })
        
      } catch (error) {
        
      }
      
      // this.showDeleteUserDialog = true
      // this.currentFriend = user;
      // this.getGroupsByMember(user)
    },
    getGroupsByMember(user){
      const { csid,wxid,wxaccount } = user
      let params = { csId:csid,wxAccount:wxaccount,memberWxId:wxid }
      this.$api.group.groupsForMemeber(params)  
        .then(data=>{
          this.groupsHasCurUser = data
        })
        .catch(e=>{
          this.$msg(e)
        })

    },

    addFriend(user) {
      console.log(user)
      const applyMsg = prompt('添加群成员 '+user.nick+' 为好友？','你好')
      if(applyMsg === null) return;
      const param = {
        memberWxId:user.wxid,
        groupNo:user.groupno,
        wxAccount:user.wxaccount,
        applyMsg,
        opType:3
      }
      this.wsSend(param)
    },
    deleteGroup() {
      this.showDismissDialog = true
    },
    comfirmDismiss() {
      this.showDismissDialog = false
      this.$api.group.dismiss({
        csid: this.service.csid,
        wxaccount: this.service.wxid,
        groupNo: this.currentGroup.wxid
      }).catch(e=>this.$msg(e))
    },
    selectGroup(e,user) {
      if (e.target.checked) {
        this.selectedDeleteGroup.push(user)
      } else {
        this.selectedDeleteGroup = this.selectedDeleteGroup.filter(u=>u.wxid!=user.wxid)
      }
    },
    comfirmDeleteUser() {
      this.showDeleteUserDialog = false
      this.selectedDeleteGroup.forEach(group=>{
        this.$api.group.removeGroupMember({
          csId: this.service.csid,
          accountWxId: this.service.wxid,
          groupNo: group.groupno,
          memberWxId: this.currentFriend.wxid
        }).then(e=>{
          this.$msg('提交成功')
        }).catch(e=>this.$msg(e))
      })
      
    },
     
  },
  computed: {
    filterGroups(){
      const isShowManager = this.groupType === 'manager'
      const keyword = pinyin.getFullChars(this.keyword).toLocaleLowerCase() 

      return this.groups.filter(item=>{
        const chars = pinyin.getFullChars(item.groupname).toLocaleLowerCase() ;
        if(isShowManager){
          return item.isfirst === 1 && chars.indexOf(keyword)>-1
        }else{
          return item.isfirst !== 1 && chars.indexOf(keyword)>-1
        }
         
      })
      
    },
    filteredUsers() {
      let filterUsers = []
      if (this.curTab == 'friend') {
        filterUsers = this.friends
      } else {
        filterUsers = this.members
      }
      if (this.searchMember == '') {
        return filterUsers
      } else {
        return filterUsers.filter(item=>item.name.indexOf(this.searchMember) > -1)
      }
    },
     
  }
}
</script>

<style scoped>
.invite-button{
  width: 141px;
  height: 30px;
  line-height: 30px;
  background-color: rgba(46, 141, 237, 1);
  box-sizing: border-box;
  font-size: 14px;
  color: #FFFFFF;
  text-align: center;
  border-radius: 3px;
  margin: 10px auto 0
}
.invite-sv{
  overflow: auto;
  /* display: inline-flex;
  flex-flow: row wrap;
  align-content: flex-start; */
}
.invite-item{
  display: flex;
  flex-direction: row;
  align-items: center;
  /* flex: 0 0 50%; */
  overflow: hidden;
  box-sizing: border-box;
  padding: 5px;
  float: left;
  width: 50%

}
.invite-avatar{
  width: 40px;
  height:40px;
  
  margin-left: 5px;
}
.invite-avatar img{
  width: 40px;
  height:40px;
  border-radius: 3px;
}
.invite-info{
  
  flex-direction: column;
  justify-content:space-between;
  display: flex;
  margin-left: 5px
}
.member-list-item{
  padding: 0 10px;
  height: 50px;
}
.member-list-item-friend{
  width: 180px;
  padding-right: 5px;  
}
.user-operate{
  justify-content:space-around;
}
.user-operate-button{
  width: 56px;
  margin-left: 0;
}
 
</style>